package hz.mobileproject.pda.ui.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.CountDownTimer;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.entity.EventTypeBean;
import hz.mobileproject.pda.entity.response.Response_BedingProcess;
import hz.mobileproject.pda.utils.DateUtils;
import hz.mobileproject.pda.utils.VirateUtil;

/**
 * Created by Lc on 2017/10/25.
 */

public class BeingProcessAdapter extends BaseAdapter {
    private Context mContext;
    private List<Response_BedingProcess> listData;
    private LayoutInflater inflater;


    private SparseArray<CountDownTimer> countDownCounters;



    public BeingProcessAdapter(Context mContext, List<Response_BedingProcess> listData) {
        this.mContext = mContext;
        this.listData = listData;
        inflater = LayoutInflater.from(mContext);
        this.countDownCounters = new SparseArray<>();
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownCounters == null) {
            return;
        }
        Log.e("TAG",  "size :  " + countDownCounters.size());
        for (int i = 0, length = countDownCounters.size(); i < length; i++) {
            CountDownTimer cdt = countDownCounters.get(countDownCounters.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }

    @Override
    public int getCount() {
        return listData == null ? 0 : listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;
        if(convertView == null){
            convertView = inflater.inflate(R.layout.layout_being_process_inlv,null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.tv_dept_name.setText(listData.get(position).dept_name);
        viewHolder.tv_grid_name.setText(listData.get(position).term_name);
        viewHolder.tv_create_time.setText(listData.get(position).start_time);
        viewHolder.prisoner_name_being.setText(listData.get(position).prisoner_name);
        viewHolder.police_name_being.setText(listData.get(position).police_name);
        String interval_time = listData.get(position).interval_time;
        viewHolder.tv_interval_time.setText(interval_time + "分钟");

        CountDownTimer countDownTimer = countDownCounters.get(viewHolder.timeTv.hashCode());
        //将前一个缓存清除
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        long timer = listData.get(position).expirationTime;
//        System.currentTimeMillis();
        timer = timer - TimeUtils.string2Millis(listData.get(position).server_time);
        //expirationTime 与系统时间做比较，timer 小于零，则此时倒计时已经结束。
        if (timer > 0) {
            countDownTimer = new CountDownTimer(timer, 1000) {
                public void onTick(long millisUntilFinished) {
                    viewHolder.timeTv.setText(DateUtils.getCountTimeByLong(millisUntilFinished));
                    viewHolder.timeTv.setTextColor(Color.WHITE);
                    setLeftColor(viewHolder,Color.parseColor("#43B0FB"));
                }
                public void onFinish() {
                    viewHolder.timeTv.setText("超时");
                    viewHolder.timeTv.setTextColor(Color.RED);
                    listData.get(position).setisChaoShi(true);
                    setLeftColor(viewHolder,Color.parseColor("#ff0000"));
                    EventBus.getDefault().post(new EventTypeBean("超时"));

                    playRingsorShoke();
                }
            }.start();
            //将此 countDownTimer 放入list.
            countDownCounters.put(viewHolder.timeTv.hashCode(), countDownTimer);
        } else {
            viewHolder.timeTv.setText("超时");
            viewHolder.timeTv.setTextColor(Color.RED);
            listData.get(position).setisChaoShi(true);
            setLeftColor(viewHolder,Color.parseColor("#ff0000"));
            EventBus.getDefault().post(new EventTypeBean("超时"));

            playRingsorShoke();

        }

        return convertView;
    }

    /**
     * 超时则播放录音或者震动
     */
    private void playRingsorShoke() {
        if(isSilentMode()) {
            //是静音模式
            VirateUtil.vibrate((Activity) mContext,2000);
        }else {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(mContext.getApplicationContext(), notification);
            r.play();
        }
    }

    private boolean isSilentMode() {
        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        return audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
    }


    public void setListData(ArrayList<Response_BedingProcess> listData){
        if(listData == null){
            listData = new ArrayList<Response_BedingProcess>();
        }
        this.listData = listData;
        notifyDataSetChanged();
    }

    public void removeData(Response_BedingProcess response_bedingProcess) {
        if(response_bedingProcess != null) {
            this.listData.remove(response_bedingProcess);
            notifyDataSetChanged();
        }
    }

    public List<Response_BedingProcess> getListData(){
        return listData;
    }


    public class ViewHolder{
        private TextView tv_dept_name;
        private TextView tv_grid_name;
        private TextView tv_create_time;
        private TextView prisoner_name_being;
        private TextView police_name_being;
        private TextView tv_interval_time;
        private TextView timeTv;
        private TextView tv1;
        private TextView tv2;
        private TextView tv3;
        private TextView tv4;
        private TextView tv5;
        private TextView tv6;
        private TextView tv7;

        public ViewHolder(View v) {
            tv_dept_name = (TextView)v.findViewById(R.id.tv_dept_name_being);
            tv_grid_name = (TextView)v.findViewById(R.id.tv_grid_name_being);
            tv_create_time = (TextView)v.findViewById(R.id.tv_create_time_being);
            prisoner_name_being  = (TextView) v.findViewById(R.id.tv_prisoner_name_being);
            police_name_being = (TextView) v.findViewById(R.id.tv_police_name_being);
            tv_interval_time = (TextView) v.findViewById(R.id.tv_interval_time);
            timeTv = (TextView) v.findViewById(R.id.tv_time);
            tv1 = (TextView) v.findViewById(R.id.tv1);
            tv2 = (TextView) v.findViewById(R.id.tv2);
            tv3 = (TextView) v.findViewById(R.id.tv3);
            tv4 = (TextView) v.findViewById(R.id.tv4);
            tv5 = (TextView) v.findViewById(R.id.tv5);
            tv6 = (TextView) v.findViewById(R.id.tv6);
            tv7 = (TextView) v.findViewById(R.id.tv7);

        }

    }

    private void setLeftColor(ViewHolder viewHolder, int color){
        viewHolder.tv1.setBackgroundColor(color);
        viewHolder.tv2.setBackgroundColor(color);
        viewHolder.tv3.setBackgroundColor(color);
        viewHolder.tv4.setBackgroundColor(color);
        viewHolder.tv5.setBackgroundColor(color);
        viewHolder.tv6.setBackgroundColor(color);
        viewHolder.tv7.setBackgroundColor(color);
    }



}
